@file:Suppress("DEPRECATION")

package com.juku2024.juku.tools

import android.content.Context
import android.net.*
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresPermission
import com.juku2024.juku.BuildConfig
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.network.NetworkType
import java.net.NetworkInterface
import java.util.*


object NetworkUtils {
    @RequiresPermission("android.permission.ACCESS_NETWORK_STATE")
    private fun getActiveNetworkInfo(context: Context): NetworkInfo? {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return cm.activeNetworkInfo
    }
    /**
     * 获取当前网络类型
     */
    fun getNetworkType(): NetworkType {
        var netType: NetworkType = NetworkType.NETWORK_NO
        val info = getActiveNetworkInfo(BaseApplication.context)
        if (info != null && info.isAvailable) {
            netType = when (info.type) {
                ConnectivityManager.TYPE_WIFI -> {
                    NetworkType.NETWORK_WIFI
                }
                ConnectivityManager.TYPE_ETHERNET -> {
                    NetworkType.NETWORK_ETHERNET
                }
                ConnectivityManager.TYPE_MOBILE -> {
                    NetworkType.NETWORK_MOBILE
                }
                else -> {
                    NetworkType.NETWORK_UNKNOWN
                }
            }
        }
        return netType
    }

    /**
     * 判断是否有网络连接
     * @param context
     * @return
     */
    fun isNetworkConnected(): Boolean {
        val info = getActiveNetworkInfo(BaseApplication.context)
        return info != null && info.isConnected
    }


    fun isNetworkTypeMobile(): Boolean {
        return getNetworkType() == NetworkType.NETWORK_MOBILE
    }



    /**
     * 获取设备蜂窝网络运营商
     *
     * @return ["中国电信CTCC":3]["中国联通CUCC:2]["中国移动CMCC":1]["other":0]["无sim卡":-1]["数据流量未打开":-2]
     */
    fun getCellularOperatorType(context: Context): Int {
        val opeType: Int
        // No sim
        if (!hasSim()) {
            opeType = -1
            return opeType
        }
        // Mobile data disabled
        if (!isMobileDataEnabled()) {
            opeType = -2
            return opeType
        }
        // Check cellular operator
        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val operator = tm.simOperator
        // 中国联通
        opeType = if ("46001" == operator || "46006" == operator || "46009" == operator) {
            2
            // 中国移动
        } else if ("46000" == operator || "46002" == operator || "46004" == operator || "46007" == operator) {
            1
            // 中国电信
        } else if ("46003" == operator || "46005" == operator || "46011" == operator) {
            3
        } else {
            0
        }
        return opeType
    }

    fun logOperator(opeType: Int): String {
        return when (opeType) {
            -2 -> "数据流量未打开"
            -1 -> "无sim卡"
            0 -> "未知的运营商"
            1 -> "中国移动"
            2 -> "中国联通"
            3 -> "中国电信"
            else -> "未知的运营商"
        }
    }

    /**
     * 判断数据流量开关是否打开
     *
     * @param context
     * @return
     */
    fun isMobileDataEnabled(): Boolean {
        return try {
            val method = ConnectivityManager::class.java.getDeclaredMethod("getMobileDataEnabled")
            method.isAccessible = true
            val connectivityManager = BaseApplication.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            method.invoke(connectivityManager) as Boolean
        } catch (t: Throwable) {
            Log.d("isMobileDataEnabled", "Check mobile data encountered exception")
            false
        }
    }

    /**
     * 检查手机是否有sim卡
     */
    fun hasSim(): Boolean {
        val tm = BaseApplication.context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val operator = tm.simOperator
        return !TextUtils.isEmpty(operator)
    }


    /**
     * 是否正在使用VPN
     */
    fun isVpnUsed(): Boolean {
        try {
            val niList = NetworkInterface.getNetworkInterfaces()
            if (niList != null) {
                for (intf in Collections.list(niList)) {
                    if (!intf.isUp || intf.interfaceAddresses.size == 0) {
                        continue
                    }
                    if ("tun0" == intf.name || "ppp0" == intf.name) {
                        return true // The VPN is up
                    }
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return false
    }
    /**
     * 判断设备 是否使用代理上网
     * return 当前网络是否开启了代理
     */
    fun isWifiProxy(): Boolean {
        if (BuildConfig.DEBUG) return false
        val proxyAddress = System.getProperty("http.proxyHost")
        val portStr = System.getProperty("http.proxyPort")
        val proxyPort = (portStr ?: "-1").toInt()
        return (!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1)
    }

}